package com.hdjk.view.callback;

import android.text.TextUtils;

import com.hdjk.view.util.UserTokenUtil;
import com.lst.projectlib.entity.Msg;
import com.zhy.http.okhttp.callback.Callback;

import org.json.JSONObject;

import okhttp3.Call;
import okhttp3.Response;

/**
 * Created by sxy on 2017/10/24.
 */

public abstract class MsgCallBack extends Callback<Msg> {

    @Override
    public Msg parseNetworkResponse(Response response, int i) throws Exception {
        Msg msg = new Msg();
        try {
            String result = response.body().string();

            if (!TextUtils.isEmpty(result)) {
                JSONObject rootObject = new JSONObject(result);
                msg.setSuccess(false);
                if ("0000".equals(rootObject.getString("code"))){
                    msg.setSuccess(true);
                    if (!rootObject.isNull("data")) {
                        Object dataJson = rootObject.get("data");
                        msg.setData(dataJson);
                    }
                }
                if ("1".equals(rootObject.getString("code"))) {
                    msg.setSuccess(true);
                    if (!rootObject.isNull("result")) {
                        Object dataJson = rootObject.get("result");
                        msg.setData(dataJson);
                    }
                }
                if (!rootObject.isNull("message")) {
                    msg.setMsg(rootObject.getString("message"));
                } else if (!rootObject.isNull("msg")) {
                    msg.setMsg(rootObject.getString("msg"));
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return msg;
    }

    @Override
    public void onError(Call call, Exception e, int i) {
        if (e.toString().contains("401")) {
            UserTokenUtil.getNewToken();
        } else if (e.toString().contains("500")){

//            ToastUtils.showLongToast(Appconfig.instance, e.toString());
        }
    }
//    public String error(Call call, Exception e, int i){
//        if (e.toString().contains("401")) {
//            UserTokenUtil.getNewToken();
//        } else if (e.toString().contains("500")){
//
////            ToastUtils.showLongToast(Appconfig.instance, e.toString());
//        }
//        return "";
//    }
}
